package com.lrj.mysecurity.service.impl;

import com.lrj.mysecurity.entity.Permission;
import com.lrj.mysecurity.entity.Role;
import com.lrj.mysecurity.entity.User;
import com.lrj.mysecurity.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //读取用户
        User user = userService.getByName(userName);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        String encodedPassword = encoder.encode(user.getPassword());

        //读取角色列表
        List<Role> roleList = userService.getRoleListByUserId(user.getId());

        //读取权限列表
        List<Permission> permissionList = userService.getPermissionListByUserId(user.getId());

        //权限数组（包含角色）
        List<String> authList = new ArrayList();

        if (roleList != null && roleList.size() > 0) {
            for (Role role : roleList) {
                authList.add("ROLE_" + role.getName());
            }
        }

        if (permissionList != null && permissionList.size() > 0) {
            for (Permission permission : permissionList) {
                authList.add(permission.getName());
            }
        }

        String[] authArr = authList.toArray(new String[authList.size()]);

        UserDetails userDetails;
        if (authArr.length > 0) {
            userDetails = org.springframework.security.core.userdetails.User.withUsername(user.getName())
                    .password(user.getPassword())
                    //必须要有角色列表，否则会报异常
                    .authorities(authArr)
                    .build();
        } else {
            userDetails = org.springframework.security.core.userdetails.User.withUsername(user.getName())
                    .password(user.getPassword())
                    //必须要有角色列表，否则会报异常
                    .roles("")
                    .build();
        }

        return userDetails;
    }
}
